import io from 'socket.io-client'

import {
  reqRegister,
  reqLogin,
  reqUpdate,
  reqUser,
  reqUserList,
  reqChatMsgList,
  reqReadMsg
} from '../api'

import {
  AUTH_SUCCESS,
  ERROR_MSG,
  RECEIVE_USER,
  RESET_USER,
  RECEIVE_USER_LIST,
  RECEIVE_MSG_LIST,
  RECEIVE_MSG,
  MSG_READ
} from './action-types'

// 使用单例模式创建socket
function initIO(dispatch,userid) {
  if (!io.socket) {
    io.socket = io('ws://localhost:4000');

    io.socket.on('receiveMsg', function (chatMsg) {
      console.log('浏览器端接收到消息', chatMsg);
      // 只有当chatMsg是与当前用户相关的消息，才去分发同步action保存消息
      if(userid === chatMsg.from || userid === chatMsg.to){
        dispatch(receiveMsg({chatMsg,userid}))
      }
    });
  }
}

//授权成功同步action
const authSuccess = (user) => ({type: AUTH_SUCCESS, data: user});

// 错误提示信息的同步action
const errorMsg = (msg) => ({type: ERROR_MSG, data: msg});

//更新信息的同步action
const receiveUser = (user) => ({type: RECEIVE_USER, data: user});

export const resetUser = (msg) => ({type: RESET_USER, data: msg});

// 接收用户列表的同步action
const receiveUserList = (userList) => ({type: RECEIVE_USER_LIST, data: userList});

// 接收消息列表的同步action
const receiveMsgList = ({users,chatMsgs,userid}) => ({type:RECEIVE_MSG_LIST,data:{users,chatMsgs,userid}});

// 接收一个消息的同步action
const receiveMsg = ({chatMsg,userid}) => ({type:RECEIVE_MSG,data:{chatMsg,userid}});

// 读取某个消息的同步action
const msgRead = ({count,from,to}) => ({type:MSG_READ,data:{count,from,to}});

// 异步获取消息列表数据
async function getMsgList(dispatch,userid) {
  initIO(dispatch,userid);
  const response = await reqChatMsgList();
  const result = response.data;
  if(result.code === 0){
    const {users,chatMsgs} = result.data;
    dispatch(receiveMsgList({users,chatMsgs,userid}));
  }
}

// 异步发送消息的action
export const sendMsg = ({from, to, content}) => {
  return () => {
    console.log('客户端向服务器发送消息', {from, to, content});
    io.socket.emit('sendMsg', {from, to, content});
  }
};

// 读取消息的异步action
export const readMsg = (from,to) => {
  return async dispatch => {
    const response = await reqReadMsg(from);
    const result = response.data;
    if(result.code === 0){
      const count = result.data;
      dispatch(msgRead({count,from,to}))
    }
  }
};


// 注册异步action
export const register = (user) => {
  const {username, password, confirm_password} = user;
  if (!username) {
    return errorMsg('请输入用户名');
  } else if (password !== confirm_password) {
    return errorMsg('两次密码不一致');
  } else if (!password) {
    return errorMsg('请输入密码');
  } else if (!confirm_password) {
    return errorMsg('请确认密码');
  }

  return async dispatch => {
    // 发送注册的异步ajax请求
    const response = await reqRegister(user);
    const result = response.data;
    if (result.code === 0) {    // 成功
      getMsgList(dispatch,result.data._id);
      dispatch(authSuccess(result.data))
    } else {   //失败
      dispatch(errorMsg(result.msg))
    }
  }
};

// 登录异步action
export const login = (user) => {
  const {username, password} = user;
  if (!username) {
    return errorMsg('请输入用户名');
  } else if (!password) {
    return errorMsg('请输入密码');
  }

  return async dispatch => {
    // 发送注册的异步ajax请求
    const response = await reqLogin(user)
    const result = response.data;
    if (result.code === 0) {    // 成功
      getMsgList(dispatch,result.data._id);
      dispatch(authSuccess(result.data))
    } else {   //失败
      dispatch(errorMsg(result.msg))
    }
  }
};

// 更新异步action
export const update = (user) => {

  return async dispatch => {
    const response = await reqUpdate(user);
    const result = response.data;
    if (result.code === 0) {    //更新成功
      dispatch(receiveUser(result.data))
    } else {     //更新失败
      dispatch(resetUser(result.msg))
    }
  }
};

// 获取用户信息异步action
export const getUser = () => {
  return async dispatch => {
    const response = await reqUser();
    const result = response.data;
    if (result.code === 0) {
      getMsgList(dispatch,result.data._id);
      dispatch(receiveUser(result.data))
    } else {
      dispatch(resetUser(result.msg))
    }
  }
};

// 获取对应用户类型的列表异步action
export const getUserList = (type) => {
  return async dispatch => {
    const response = await reqUserList(type);
    const result = response.data;
    if (result.code === 0) {
      dispatch(receiveUserList(result.data))
    }
  }
};

